#include <blackbox/blackbox.h>
#include <blackbox/boxes/bperiodic.h>
#include <blackbox/cscheduler.h>
#include <blackbox/proxies.h>
#include <blackbox/connect.h>

#include <buola/media/codec/bffmpegencoder.h>
#include <buola/media/video/bvideotestsrc.h>
#include <blackbox/boxes/io/bfilesrc.h>
#include <blackbox/boxes/io/bfilesink.h>
#include <buola/media/audio/bpulsesink.h>
#include <buola/media/codec/bmp3decoder.h>
#include <blackbox/boxes/bdiskimagewriter.h>
#include <blackbox/boxes/bimagedisplay.h>
#include <buola/app/ccmdline.h>

using namespace buola;
using namespace buola::blackbox;

class CTestFfmpegMachine
{
public:
    CTestFfmpegMachine()
        :   mFileSink(io::file("tonto.mkv"))
    {
        msg_info() << "creating machine!!!\n";
        mEncoder.SetFormat("matroska");
        mEncoder.AddVideoStream("libx264",CSize_i(640,480));
        bb_connect(mVideoSrc.oImage,*mEncoder.iVideo[0]);
        bb_connect(mVideoSrc.kOut,*mEncoder.kVideo[0]);
        bb_connect(mEncoder.oData,mFileSink.iData);
        mEncoder.ChangeState(BBox::STATE_ACTIVE);

        thread([this]{LoopThread();}).detach();
    }

    void LoopThread()
    {
        while(true)
        {
            mVideoSrc.CreateImage();
            sleep(50_ms);
        }
    }

private:
    BVideoTestSrc mVideoSrc;
    media::BFfmpegEncoder mEncoder;
    BFileSink mFileSink;
};

int main(int pNArgs,char **pArgs)
{
    buola_init(pNArgs,pArgs);

    try
    {
        CTestFfmpegMachine lMachine;
        buola_main_loop();
    }
    catch(std::exception &pE)
    {
        msg_error() << "caught exception " << pE.what() << "\n";
    }

    return buola_finish();
}
